<!-- m_sales.ftl  -->
var MSales = {
    u: '/mSales'
    , uList: '/mSales/list'
    , uEdit: '/mSales/edit'
    , uDel: '/mSales/delete'
};

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o) if (new RegExp("(" + k + ")").test(format))
        format = format.replace(RegExp.$1,
            RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};
MSales.isEmpty = function (value) {
    if (value == undefined || value == null || value == "") {
        return true;
    }
    return false;
}

MSales.dg = function () {
    var grid = new $yd.DataGrid(this.dtable);
    grid.onDblClickRow = function (index, row) {
        // MSales._edit(row['id']);
        MSales.windowDetail(row['id']); // 双击打开详情
    };
    grid.onClickRow = function (index,row) {
        $(this).datagrid('unselectRow', index);
        MSales.goodsTable.datagrid("reload", {
            saleId: row.id,

        });

    };
    grid.checkOnSelect = false;
    grid.singleSelect = true;
    grid.nowarp = false;
    grid.url = MSales.uList;
    grid.rownumbers = true;
    // grid.scrollbarSize = 0;
    // grid.fitColumns = true;
    grid.columns = [[
        {field: 'id', checkbox: true}
        , {field: 'code', title: '销售单号', width: 82,halign:'center',align:'center'}
        , {field: 'orderTime', title: '开单时间', width: 80,halign:'center',align:'center', formatter: function (value) {
            return $yd.isEmpty(value) ? "" : value.substr(0, 10);
        }}
        , {field: 'username', title: '开单人', width: 80,halign:'center',align:'center'}
        , {field: 'cusName', title: '客户名称', width: 80,halign:'center',align:'center'}
        // , {field: 'cusAddr', title: '客户地址', width: 80}
        // , {
        //     field: 'orderTime', title: '订单日期', width: 80, formatter: function (value) {
        //         return new Date(value).format('yyyy-MM-dd');
        //     }
        // }
        , {
            field: 'goodsName', title: '商品摘要', width: 120,halign:'center',align:'center', formatter: function (value) {
                return MSales.formatDetail(value);
            }
        }
        , {field: 'totalNum', title: '销售总数', width: 60,halign:'center',align:'center'}
        , {field: 'totalFee', title: '应收总额', width: 60,halign:'center',align:'center', formatter: function (value, row, index) {
                return Number(value).toFixed(2);
            }}
        , {field: 'payFee', title: '实收金额', width: 60,halign:'center',align:'center', formatter: function (value, row, index) {
            return Number(value).toFixed(2);
        }}
        , {
            field: 'payStatus', title: '结清状态', width: 60,halign:'center',align:'center', formatter: function (value) {
                if (value == 0) {
                    return '<label class="label label-warning">未结清</label>';
                } else {
                    return '<label class="label label-default">已结清</label>';
                }
            }
        }, {
            field: 'orderStatus', title: '是否出库', width: 60,halign:'center',align:'center', formatter: function (value) {
                if (value == 0) {
                    return '<label class="label label-warning">待出库</label>';
                } else if (value == 1){
                    return '<label class="label label-default">已出库</label>';
                }else if (value == 3){
                    return '<label class="label label-primary">已退货</label>';
                }
            }
        }
        // , {field: 'remark', title: '备注', width: 80,halign:'center',align:'center'}
        , {field: 'ctime', title: '创建时间', width: 80,halign:'center',align:'center'}
    ]];
    grid.loadGrid();
};

MSales.windowDetail = function (saleId) {
    var dg = $yd.win3.create('销售单详情', "/mSales/detailPage?saleId=" + saleId);
    dg.width = "70%";
    dg.height = "80%";
    dg.open(function (that, $win) {

    });
};

MSales.formatDetail = function (value) {
    if (MSales.isEmpty(value)) {
        return "";
    }
    var result = "";
    var first = "";
    var arr = value.split(",");
    if (arr.length == 1) {
        return "<a style='color:blue' title='" + value + "'>" + value + "</a>";
    }
    for (var i = 0; i < arr.length; i++) {
        result += arr[i] + "\n";
        if (i == 0) {
            first = result;
        }
    }
    var html = "<a style='color:blue' title='" + result + "'>" + first + "..." + "</a>";

    return html;
};
MSales.dg.getOne = function () {
    var sels = MSales.dg.getSels();
    if (sels.length === 1) {
        return sels[0];
    }
    return null;
};
MSales.dg.getSels = function () {
    return MSales.dtable.datagrid('getSelections');
};
// 重置
MSales.reset = function () {
    $("form.search-form").form('clear');
    MSales.search();
}
// 处理按钮
MSales.btn = function () {
    var sb = new $yd.SearchBtn($(MSales.obtn));
    // sb.create('remove', '', MSales.remove);
    // sb.create('remove', '发货', MSales.remove);
    sb.create('cut green', '整单退货', MSales.allReturn);
    sb.create('repeat red', '重置', MSales.reset);
    sb.create('print green', '打印', MSales.print);
    // sb.create('refresh', '刷新', MSales.refresh);
    // sb.create('edit', '编辑', MSales.edit);
    sb.create('remove', '删除', MSales.remove);
    sb.create('plus', '新增', MSales.plus);
    // sb.create('search', '查询', MSales.search);
};
//整单退货
MSales.allReturn = function () {

    var sels = MSales.dg.getSels();
    if (sels.length != 1) {
        $yd.alert('请选择一条记录');
        return;
    }

    var ids = [];
    for (var i = 0; i < sels.length; i++) {
        var n = sels[i];
        if (n.orderStatus == 0) {
            $yd.alert('未出库无需整单退货');
            return;
        }
        if (n.orderStatus == 3) {
            $yd.alert('此单已退货，不能重复退货');
            return;
        }
        ids.push(n['id']);
    }

    $yd.confirm("确定对此单进行整单退货吗？",function () {
        var ids = [];
        $.each(sels, function (i, n) {
            ids.push(n['id']);
        });
        $yd.post("/saleReturn/allReturn", {id: ids}, function (data) {
            $yd.alert("生成销售退货单成功",function () {
                parent.inv.OpenPage("/saleReturn?searchText="+data , "<i class=\"menu-icon fa fa-flag\"></i>\n" +
                    "<span class=\"menu-text\">销售退货</span>\n" +
                    "<b class=\"arrow \"></b>", true)
            })

        });
    })
};
//删除
MSales.remove = function () {
    var sels = MSales.dtable.datagrid('getChecked')
    if (sels.length < 1) {
        $yd.alert('选中记录');
        return;
    }
    var ids = [];
    for(var i=0; i<sels.length; i++) {
        if(sels[i].orderStatus == 1) {
            $yd.alert('已出库不能删除');
            return;
        }
        if(sels[i].orderStatus == 3) {
            $yd.alert('已退货不能删除');
            return;
        }
        if(sels[i].payStatus != 0) {
            $yd.alert('已支付不能删除');
            return;
        }
        ids.push(sels[i].id);
    }
    $yd.confirm(function () {
        $.post(MSales.uDel, {ids: ids}, function (data) {
            if($yd.isEmpty(data.message) || data.message == "操作成功") {
                $yd.alert("操作成功", function () {
                    MSales.search();
                })
            } else {
                $yd.alert(data.message);
            }
        });
    })
};

//打印
MSales.print = function () {
    var sel = MSales.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    MSales._print(sel['id'])
};
MSales._print = function (id) {
    parent.inv.OpenPage("/mSales/print?id=" + id, "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "                                <span class=\"menu-text\"> 打印销售单 </span>\n" +
        "                                <b class=\"arrow \"></b>", true)
};
//
MSales.edit = function () {
    var sel = MSales.dg.getOne();
    if (!sel) {
        $yd.alert('请选择一条记录');
        return;
    }
    MSales._edit(sel['id'])
};
// 表单预处理
MSales.preForm = function () {
    new $yd.combobox("customerId").load("/customer/select");
};
MSales._edit = function (id) {
    parent.inv.OpenPage("/mSales/edit?id=" + id, "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "                                <span class=\"menu-text\"> 销售单详情 </span>\n" +
        "                                <b class=\"arrow \"></b>", true)
};
//新增
MSales.plus = function () {
    parent.inv.OpenPage("/mSales/addSales", "<i class=\"menu-icon fa fa-flag\"></i>\n" +
        "                                <span class=\"menu-text\"> 新增销售单 </span>\n" +
        "                                <b class=\"arrow \"></b>", true)
};
//
MSales.refresh = function () {
    window.location.reload();
};
//搜索
MSales.search = function () {
    MSales.dtable.datagrid('load', MSales.sform.serializeObject());
};
MSales.goodsTableFun = function () {

    var grid = new $yd.DataGrid(MSales.goodsTable);
    grid.url ='/mSales/detailGoodsList';
    grid.rownumbers = true;
    grid.singleSelect = true;
    grid.columns = [[
        {field: 'goodsName', title: '商品名称', width: 220},
        {field: 'skus', title: '规格', width: 220},
        {field: 'goodsId', title: '商品ID', width: 80, hidden: true},
        {field: 'goodsCode', title: '商品编号', width: 80},
        {field: 'OECode', title: 'OE编号', width: 120},
        {field: 'suitCar', title: '适用车型', width: 90},
        {field: 'wearhouseName', title: '仓库', width: 90},
        // {field: 'batchCode', title: '批号', width: 90},
        {field: 'unitPrice', title: '销售单价', width: 50},
        {
            field: 'count',
            title: '销售数量',
            width: 50
        },
        {
            field: 'shouldPay', title: '总额', width: 50, formatter: function (value, row, index) {
            return (Number(row.count) * Number(row.unitPrice)).toFixed(2);
        }
        }
    ]]
    grid.loadGrid();
}

$(function () {
    MSales.sform = $('#mSales_form');
    MSales.dtable = $('#mSales_table');
    MSales.goodsTable = $('#saleGoods_table');
    MSales.obtn = '#mSales_btn';
    MSales.goodsTableFun();
    MSales.dg(); // 数据表格
    MSales.btn(); // 初始化按钮
    $yd.bindEnter(MSales.search);
    $("#searchButton").click(MSales.search);

    if(!$yd.isEmpty($("#hidSearchText").val())) {
        $("#searchText").textbox("setValue", $("#hidSearchText").val());
        $("#startTime").datebox("setValue", $("#hidStartTime").val());
        $("#endTime").datebox("setValue", $("#hidEndTime").val());
        setTimeout("MSales.search()", 10);
    }
    $("input[name='payStatus']").combobox({
        url: "/sysDict/sales_pay_status",
        panelHeight: 'auto',
        valueField: 'id',
        textField: 'text',
        editable: false,
    });

    $("input[name='orderStatus']").combobox({
        url: "/sysDict/sales_order_status",
        panelHeight: 'auto',
        valueField: 'id',
        textField: 'text',
        editable: false,
    });
});